package com.tubeonfire.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tubeonfire.entity.Channel;
import com.tubeonfire.entity.Tube;
import com.tubeonfire.model.admin.ChannelModel;
import com.tubeonfire.model.admin.TubeModel;
import com.tubeonfire.search.admin.TubeSearchModel;
import com.tubeonfire.service.YoutubeService;
import com.tubeonfire.util.ApplicationHelper;
import com.tubeonfire.util.TagHelper;

@SuppressWarnings("serial")
public class TaskQueueServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(TaskQueueServlet.class
			.getName());

	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		if (ApplicationHelper.getApplicationType() == 2) {
			try {
				String action = req.getParameter("action");
				if (action != null && action.equals("add-when-search")) {
					if (req.getParameter("key") != null) {
						if (YoutubeService.isStartedCache()
								&& YoutubeService.getCache() != null) {
							String key = req.getParameter("key");
							key = key.replace(" ", "+");
							System.out.println(key);
							List<Tube> list = (ArrayList<Tube>) YoutubeService
									.getCache().get(key);
							if (list != null) {
								for (Tube tube : list) {
									if (TubeSearchModel.getById(tube.getId()) == null) {
										tube = processTubeDetail(tube);
										TubeModel.insert(tube);
									}
								}
							}
						}
					}
				}
			} catch (Exception e) {
				log.warning(e.toString());
				e.printStackTrace();
			}
		}
	}

	private Tube processTubeDetail(Tube tube) {
		tube.setTags(TagHelper.youTag(tube.getTitle() + " "
				+ tube.getDescription()));
		tube.setOtherTags(TagHelper.getOtherTag(tube.getTags()));
		tube.setBumpPoint(Calendar.getInstance().getTimeInMillis() / 1000);
		if (ChannelModel.getById(tube.getChannelId()) == null) {
			Channel channel = new Channel();
			channel.setId(tube.getChannelId());
			channel.setTitle(tube.getChannelName());
			channel.setDescription(tube.getChannelName());
			channel.setDoc(Calendar.getInstance().getTime());
			channel.setUpdated(Calendar.getInstance().getTime());
			channel.setBumpPoint(Calendar.getInstance().getTimeInMillis() / 1000);
			channel.setStatus(1);
			ChannelModel.insert(channel);
		}
		return tube;
	}
}
